package com.gking.centerSystem.interceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gking.centerSystem.common.BaseContext;

import com.gking.centerSystem.common.Result;
import com.gking.centerSystem.utils.AccessPolicyUtil;
import com.gking.centerSystem.utils.commonUtil.JsonUtils;
import com.gking.centerSystem.utils.LogRecordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


/**
 * 请求拦截器
 */
@Slf4j
public class RequestInterceptor implements HandlerInterceptor {

    private static final String REQUEST_START_TIME_ATTRIBUTE = "REQUEST_START_TIME";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) {
        // 在请求开始时记录当前时间, 存储纳秒级别的开始时间戳
        request.setAttribute(REQUEST_START_TIME_ATTRIBUTE, System.nanoTime());

//        AccessPolicyUtil accessPolicyUtil = new AccessPolicyUtil();
//        Boolean blackPolicy = accessPolicyUtil.BlackPolicy(request);
//        Boolean whitePolicy = accessPolicyUtil.WhitePolicy(request);
//        Boolean greyPolicy = accessPolicyUtil.GreyPolicy(request);
//        Boolean frequencyAccessPolicy = accessPolicyUtil.FrequencyAccessPolicy(request);
//        log.info("blackPolicy : {} ", blackPolicy);
//        log.info("whitePolicy : {} ", whitePolicy);
//        log.info("greyPolicy : {} ", greyPolicy);
//        log.info("frequencyAccessPolicy : {} ", frequencyAccessPolicy);
//
//        if (!blackPolicy) return false;
//        if (whitePolicy) return true;
//        if (!greyPolicy) return false;
//        if (!frequencyAccessPolicy) return false;

        return true; // 继续处理请求
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) {
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) {

        // if (BaseContext.getResponseBody() == null) {
        //     BaseContext.destroy();
        //     return;
        // }

        // 日志记录
        LogRecordUtil logRecordUtil = new LogRecordUtil(request, response);
        logRecordUtil.logRecord(REQUEST_START_TIME_ATTRIBUTE);


//        log.info("Request completed : {} ", BaseContext.getResponseBody());
//        // 通过请求响应结果，进行判断是否需要进行 IP 控制
//        Result deserialize = JsonUtils.deserialize(BaseContext.getResponseBody(), Result.class);
//        assert deserialize != null;
//        AccessPolicyUtil accessPolicyUtil = new AccessPolicyUtil();
//        accessPolicyUtil.judgeIpControlled(deserialize, request);


        //
        //销毁保存的数据
        BaseContext.destroy();
    }

}
